import base64
import datetime
from contextlib import contextmanager

from flask_httpauth import HTTPBasicAuth
from flask_login import login_user, logout_user, login_required, current_user
from flask import render_template, json, jsonify, request, abort, session, g, appcontext_pushed
from . import main
from ..models import User,Group,Action,Authority


'''
@contextmanager
def user_set(app, user):
    def handler(sender, **kwargs):
        g.user = user
    with appcontext_pushed.connected_to(handler, app):
        yield

'''


@main.route('/', methods=['GET', 'POST'])
def index():
    return render_template('index.html')

@main.route('/app/login', methods=['GET', 'POST'])
def user_login():
    data = request.get_json()
    #data = json.loads(request.get_data())
    username = data['username']
    password = data['password']
    user = User.query.filter_by(username=username).first()
    _pswd = base64.b64decode(password)

    info = dict()
    if user is  None :
        info['code']='404'
        info['message']='用户不存在'
    elif user.verify_password(_pswd):

        info['code']='200'
        info['message']='ok'
        session['user_id'] = user.id
        login_user(user, remember=True)
    else:

        info['code']='500'
        info['message']='用户名或密码错误！'
    return jsonify(info)


@main.route('/app/logout')
#@login_required
def logout():
    logout_user()
    session.pop('user_id', None)
    return jsonify({'data':'True'})

